<template>
  <div class="orchestrate-visualized-index-ctn">
    <el-container style="height: 100%">
      <el-aside class="graph-aside" width="140px">
        <item-box />
      </el-aside>
      <el-container style="height: 100%; padding-top: 5px; padding-left: 12px">
        <el-header>
          <div class="operate-group">
            <el-button
              type="primary"
              size="medium"
              @click="saveTemplate"
            >保存模板</el-button>
            <el-button
              type="success"
              size="medium"
              style="margin-right: 20px"
              @click="orderClick"
            >一键编排</el-button>
          </div>
        </el-header>
        <el-main
          v-loading="mainLoading"
          element-loading-background="rgba(4, 63, 92, 0.5)"
          style="height: calc(100% - 80px)"
        >
          <graph-arrange
            :graph-api="GraphApi"
            @handleNode="handleNode"
            @handleLink="() => {}"
          />
        </el-main>
      </el-container>
    </el-container>
    <graph-nodes-config ref="graphNodesConfig" />

    <!-- 一键编排 -->
    <el-dialog
      class="create-dialog"
      :title="'一键编排'"
      :visible.sync="showDialogOrder"
      width="35vw"
      top="15vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="showDialogOrder = false"
    >
      <el-form
        ref="formOrder"
        :rules="rules"
        :model="formOrder"
        label-width="auto"
        size="medium"
      >
        <el-form-item label="业务名称" prop="name">
          <el-input v-model="formOrder.name" placeholder="请输入业务名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="showDialogOrder = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="confirmLoadingOrder"
          @click="confirmClickOrder"
        >订购</el-button>
      </div>
    </el-dialog>

    <!-- 保存模板 -->
    <el-dialog
      class="create-dialog"
      :title="'保存模板'"
      :visible.sync="showDialogTemplate"
      width="35vw"
      top="15vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="showDialogTemplate = false"
    >
      <el-form
        ref="formTemplate"
        :rules="rules"
        :model="formTemplate"
        label-width="auto"
        size="medium"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input
            v-model="formTemplate.name"
            placeholder="请输入模板名称"
            :disabled="isTemplateUpdate"
          />
        </el-form-item>
        <el-form-item label="模板描述" prop="desc">
          <el-input
            v-model="formTemplate.desc"
            placeholder="请输入模板描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="showDialogTemplate = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="confirmLoadingTemplate"
          @click="confirmClickTemplate"
        >保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import GraphApi from '@/graph/graphApi'
import graphArrange from '@/components/mainGraph/graph'
import itemBox from '@/components/mainGraph/item-box.vue'
import graphNodesConfig from '@/components/mainGraph/graph-nodes-config.vue'
import {
  createOrchestrateTemplate,
  updateOrchestrateTemplate,
  detailOrchestrateTemplate,
  orderOrchestrate
} from '@/api/orchestrate'
import { isEmptyString } from '@/utils/index'

export default {
  name: 'OrchestrateVisualizedIndex',
  components: {
    graphArrange,
    itemBox,
    graphNodesConfig
  },
  data() {
    return {
      GraphApi: new GraphApi(),
      mainLoading: false,
      orchestratedId: '', // 已编排id
      showDialogOrder: false,
      confirmLoadingOrder: false,
      formOrder: {
        name: ''
      },
      templateId: '', // 模板id
      showDialogTemplate: false,
      confirmLoadingTemplate: false,
      formTemplate: {
        name: '',
        desc: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            pattern: /^[\u4e00-\u9fa5\-_a-zA-Z0-9]{1,64}$/,
            message:
              '长度范围为1-64位，只能由中文、英文字母、数字、下划线、中划线'
          }
        ]
      }
    }
  },
  computed: {
    /**
     * @description: 是否是更新模板
     * @return {*}
     */
    isTemplateUpdate() {
      return !isEmptyString(this.templateId)
    }
  },
  created() {},
  mounted() {
    this.initData()
  },
  methods: {
    /**
     * @description: 订购
     * @return {*}
     */
    confirmClickOrder() {
      this.$refs.formOrder.validate((valid, obj) => {
        if (valid) {
          this.confirmLoadingOrder = true
          const GraphApi = this.GraphApi
          const viewXml = GraphApi.getXML()
          const viewJsonObj = GraphApi.getGraphMeta()
          orderOrchestrate({
            name: this.formOrder.name,
            templateContent: viewXml,
            templateJson: JSON.stringify(viewJsonObj)
          })
            .then((res) => {
              this.showDialogTemplate = false
              this.$message.success({
                message: '订购成功！',
                duration: '1500'
              })
              setTimeout(() => {
                this.$router.push({
                  name: 'OrchestrateVisualizedList'
                })
              }, 1000)
            })
            .finally(() => {
              this.confirmLoadingOrder = false
            })
        }
      })
    },
    /**
     * @description: 一键订阅
     * @return {*}
     */
    orderClick() {
      this.$refs.formOrder && this.$refs.formOrder.resetFields()
      this.showDialogOrder = true
    },
    /**
     * @description: 保存模板-确定
     * @return {*}
     */
    confirmClickTemplate() {
      this.$refs.formTemplate.validate((valid, obj) => {
        if (valid) {
          this.confirmLoadingTemplate = true
          const GraphApi = this.GraphApi
          const viewXml = GraphApi.getXML()
          const viewJsonObj = GraphApi.getGraphMeta()
          if (this.templateId) {
            // 更新
            updateOrchestrateTemplate({
              id: this.templateId,
              desc: this.formTemplate.desc,
              templateContent: viewXml,
              templateJson: JSON.stringify(viewJsonObj)
            })
              .then((res) => {
                this.showDialogTemplate = false
                this.$message.success({
                  message: '保存模板成功！',
                  duration: '1500'
                })
                setTimeout(() => {
                  this.$router.push({
                    name: 'OrchestrateVisualizedTemplate'
                  })
                }, 1000)
              })
              .finally(() => {
                this.confirmLoadingTemplate = false
              })
          } else {
            // 创建
            createOrchestrateTemplate({
              name: this.formTemplate.name,
              desc: this.formTemplate.desc,
              templateContent: viewXml,
              templateJson: JSON.stringify(viewJsonObj)
            })
              .then((res) => {
                this.showDialogTemplate = false
                this.$message.success({
                  message: '保存模板成功！',
                  duration: '1500'
                })
                setTimeout(() => {
                  this.$router.push({
                    name: 'OrchestrateVisualizedTemplate'
                  })
                }, 1000)
              })
              .finally(() => {
                this.confirmLoadingTemplate = false
              })
          }
        }
      })
    },
    /**
     * @description: 保存模板
     * @return {*}
     */
    saveTemplate() {
      this.$refs.formTemplate && this.$refs.formTemplate.resetFields()
      this.showDialogTemplate = true
    },
    handleNode(cell) {
      const parentCell = cell.parent
      if (parentCell.type === 'cloud') {
        const busD = JSON.parse(parentCell.businessData || '{}')
        const cloudType = busD.attribute ? busD.attribute.cloudProvider : ''
        if (!cloudType) {
          this.$message.warning('请先配置云商信息')
          return false
        }
      }
      this.$refs.graphNodesConfig.showDialog(cell, this.GraphApi)
    },
    /**
     * @description: 获取模板详情
     * @return {*}
     */
    getTemplateDetail() {
      this.mainLoading = true
      detailOrchestrateTemplate({
        id: this.templateId
      })
        .then((res) => {
          if (
            res.data &&
            !isEmptyString(res.data.name) &&
            !isEmptyString(res.data.templateContent)
          ) {
            this.formTemplate.name = res.data.name
            this.formTemplate.desc = res.data.desc || ''
            const graph = this.GraphApi
            graph.setXmlValue(res.data.templateContent)
            graph.getGraph().zoomTo(1)
            graph.getGraph().center()
          } else {
            this.$message.error('模板数据异常')
          }
        })
        .finally(() => {
          this.mainLoading = false
        })
    },
    /**
     * @description: 初始化
     * @return {*}
     */
    initData() {
      this.templateId = this.$route.query.templateId || ''
      if (!isEmptyString(this.templateId)) {
        this.getTemplateDetail()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/theme-dark.less";
@import "@/assets/css/common.less";
.orchestrate-visualized-index-ctn {
  height: calc(100vh - 50px);
  width: 100%;
  background-image: url("/img/graph/bg.png");
  background-size: 100% 100%;
  .graph-aside {
    height: auto;
    padding-top: 35px;
    margin-top: 5px;
    margin-bottom: 5px;
    background: url("~@/assets/imgs/graph/a-left.png") no-repeat center;
    background-size: 100% 100%;
  }

  .operate-group {
    background-image: url("~@/assets/imgs/graph/t-f.png");
    background-size: 100% 100%;
    height: 70px;
    line-height: 70px;
    text-align: right;
    margin-right: 5%;
    width: 100%;
    z-index: 99;
  }

  /deep/ .el-main {
    padding: 20px 2px 2px 2px;
  }

  /deep/ .el-header {
    padding: 2px;
  }
}
</style>
